/*==============================================================================
案例5：产品定价策略分析（H2O GBM + SHAP）
文件: case05_pricing_strategy.do
==============================================================================*/

clear all
set more off
capture log close

* 设置工作目录
cd "/Users/mac/git/stata"

* 创建输出目录
capture mkdir output
capture mkdir output/figures

* 开始日志
log using "output/case05_pricing_h2o.log", replace text

display "=========================================="
display "=========================================="

/*------------------------------------------------------------------------------
第一步：数据准备
------------------------------------------------------------------------------*/

display ""
display "第一步：数据准备"

* 创建模拟产品数据
set seed 12345
set obs 1000

* 产品特征
gen cost = rnormal(50, 15)
gen quality_score = int(runiform() * 5) + 1
gen brand_strength = runiform()
gen market_share = runiform() * 0.3

* 竞争因素
gen competitor_price = rnormal(100, 20)
gen num_competitors = int(runiform() * 10) + 1

* 市场因素
gen demand_index = rnormal(100, 20)
gen seasonality = sin(_n / 100 * 2 * _pi)

* 生成价格（真实关系）
gen price = cost * 1.5 + ///
    quality_score * 10 + ///
    brand_strength * 30 + ///
    competitor_price * 0.3 + ///
    demand_index * 0.2 + ///
    seasonality * 15 + ///
    rnormal(0, 5)

replace price = max(cost * 1.1, price)

* 创建产品类别
gen product_category = int(runiform() * 3) + 1
label define cat_lbl 1 "电子产品" 2 "家居用品" 3 "服装配饰"
label values product_category cat_lbl

* 创建价格段
gen price_segment = 1 if price < 80
replace price_segment = 2 if price >= 80 & price < 120
replace price_segment = 3 if price >= 120 & price < 160
replace price_segment = 4 if price >= 160 & !missing(price)
label define seg_lbl 1 "低价" 2 "中低价" 3 "中高价" 4 "高价"
label values price_segment seg_lbl

display ""
summarize price cost quality_score brand_strength competitor_price demand_index

display ""
tabulate product_category

display ""
tabulate price_segment

/*------------------------------------------------------------------------------
第1.5步：探索性数据分析
------------------------------------------------------------------------------*/

display ""
display "第1.5步：探索性数据分析"

* 价格分布
histogram price, ///
    title("产品价格分布") ///
    xtitle("价格（元）") ///
    ytitle("频率") ///
    normal ///
    scheme(s2color)
graph export "output/figures/case05_01_price_distribution.png", replace width(1200)

* 价格 vs 成本
twoway (scatter price cost, msize(small) mcolor(blue%30)) ///
       (lfit price cost, lcolor(red)), ///
    title("价格 vs 成本关系") ///
    xtitle("成本（元）") ///
    ytitle("价格（元）") ///
    legend(order(1 "实际数据" 2 "拟合线")) ///
    scheme(s2color)
graph export "output/figures/case05_02_price_vs_cost.png", replace width(1200)

* 价格 vs 竞争对手价格
twoway (scatter price competitor_price, msize(small) mcolor(green%30)) ///
       (lfit price competitor_price, lcolor(red)), ///
    title("价格 vs 竞争对手价格") ///
    xtitle("竞争对手价格（元）") ///
    ytitle("我方价格（元）") ///
    legend(order(1 "实际数据" 2 "拟合线")) ///
    scheme(s2color)
graph export "output/figures/case05_03_price_vs_competitor.png", replace width(1200)

* 按质量评分的价格箱线图
graph box price, over(quality_score) ///
    title("不同质量评分的价格分布") ///
    ytitle("价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_04_price_by_quality.png", replace width(1200)

* 按产品类别的价格对比
graph box price, over(product_category) ///
    title("不同产品类别的价格分布") ///
    ytitle("价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_05_price_by_category.png", replace width(1200)

* 品牌强度对价格的影响
gen brand_group = 1 if brand_strength < 0.33
replace brand_group = 2 if brand_strength >= 0.33 & brand_strength < 0.67
replace brand_group = 3 if brand_strength >= 0.67 & !missing(brand_strength)
label define brand_lbl 1 "弱品牌" 2 "中等品牌" 3 "强品牌"
label values brand_group brand_lbl

graph box price, over(brand_group) ///
    title("品牌强度对价格的影响") ///
    ytitle("价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_06_price_by_brand.png", replace width(1200)

/*------------------------------------------------------------------------------
第二步：初始化H2O
------------------------------------------------------------------------------*/

display ""
display "第二步：初始化H2O"
display "----------------"

h2o init

* 导入数据到H2O
_h2oframe put, into(pricing_data) current

* 划分训练/测试集
_h2oframe split pricing_data, into(train test) split(0.8 0.2) rseed(123)
_h2oframe change train

/*------------------------------------------------------------------------------
第三步：训练GBM模型
------------------------------------------------------------------------------*/

display ""
display "第三步：训练GBM模型（带超参数调优）"

h2oml gbregress price cost quality_score brand_strength market_share ///
    competitor_price num_competitors demand_index seasonality, ///
    h2orseed(123) cv(5) ///
    ntrees(50(50)200) ///
    lrate(0.05(0.05)0.2) ///
    maxdepth(3(1)7) ///
    tune(metric(rmse) grid(random) maxmodels(20))

* 保存模型
h2omlest store gbm_pricing

* 查看性能
display ""
h2omlestat metrics

/*------------------------------------------------------------------------------
第四步：SHAP分析（可解释性）
------------------------------------------------------------------------------*/

display ""
display "第四步：SHAP分析"

* 变量重要性
h2omlgraph varimp, ///
    title("定价因素重要性排名") ///
    scheme(s2color)
graph export "output/figures/case05_07_varimp.png", replace width(1200)

* SHAP汇总图
h2omlgraph shapsummary, ///
    title("定价因素SHAP值分析") ///
    scheme(s2color)
graph export "output/figures/case05_08_shap_summary.png", replace width(1200)

* 部分依赖图 - 成本
h2omlgraph pdp cost, ///
    title("成本对价格的边际影响") ///
    xtitle("成本（元）") ///
    ytitle("预测价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_09_pdp_cost.png", replace width(1200)

* 部分依赖图 - 竞争对手价格
h2omlgraph pdp competitor_price, ///
    title("竞争对手价格的影响") ///
    xtitle("竞争对手价格（元）") ///
    ytitle("预测价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_10_pdp_competitor.png", replace width(1200)

* 部分依赖图 - 品牌强度
h2omlgraph pdp brand_strength, ///
    title("品牌强度对价格的影响") ///
    xtitle("品牌强度（0-1）") ///
    ytitle("预测价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_11_pdp_brand.png", replace width(1200)

* 部分依赖图 - 质量评分
h2omlgraph pdp quality_score, ///
    title("质量评分对价格的影响") ///
    xtitle("质量评分（1-5）") ///
    ytitle("预测价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_12_pdp_quality.png", replace width(1200)

* 部分依赖图 - 需求指数
h2omlgraph pdp demand_index, ///
    title("需求指数对价格的影响") ///
    xtitle("需求指数") ///
    ytitle("预测价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_13_pdp_demand.png", replace width(1200)

* 部分依赖图 - 市场份额
h2omlgraph pdp market_share, ///
    title("市场份额对价格的影响") ///
    xtitle("市场份额（0-0.3）") ///
    ytitle("预测价格（元）") ///
    scheme(s2color)
graph export "output/figures/case05_14_pdp_market_share.png", replace width(1200)

/*------------------------------------------------------------------------------
第4.5步：预测和评估
------------------------------------------------------------------------------*/

display ""
display "第4.5步：模型预测和评估"
display "------------------------"

* 在测试集上预测
_h2oframe change test
h2omlpredict price_pred, model(gbm_pricing)

* 获取测试集结果
_h2oframe get test, into(test_results) replace

* 计算预测误差
gen prediction_error = price - price_pred
gen abs_error = abs(prediction_error)
gen pct_error = (abs_error / price) * 100

display ""
summarize price price_pred prediction_error abs_error pct_error

* 实际值 vs 预测值散点图
twoway (scatter price price_pred, msize(small) mcolor(blue%30)) ///
       (function y=x, range(price) lcolor(red) lpattern(dash)), ///
    title("实际价格 vs 预测价格") ///
    xtitle("预测价格（元）") ///
    ytitle("实际价格（元）") ///
    legend(order(1 "预测结果" 2 "完美预测线")) ///
    scheme(s2color)
graph export "output/figures/case05_15_actual_vs_predicted.png", replace width(1200)

* 预测误差分布
histogram prediction_error, ///
    title("预测误差分布") ///
    xtitle("预测误差（元）") ///
    ytitle("频率") ///
    normal ///
    scheme(s2color)
graph export "output/figures/case05_16_error_distribution.png", replace width(1200)

* 按价格段的预测准确性
graph box abs_error, over(price_segment) ///
    title("不同价格段的预测误差") ///
    ytitle("绝对误差（元）") ///
    scheme(s2color)
graph export "output/figures/case05_17_error_by_segment.png", replace width(1200)

/*------------------------------------------------------------------------------
第五步：定价策略分析
------------------------------------------------------------------------------*/

display ""
display "第五步：定价策略分析"

* 计算成本加成率
gen markup_rate = (price - cost) / cost * 100

* 计算相对竞争对手的价格差异
gen price_diff_pct = (price - competitor_price) / competitor_price * 100

display ""
summarize markup_rate, detail

display ""
summarize price_diff_pct, detail

* 成本加成率分布
histogram markup_rate, ///
    title("成本加成率分布") ///
    xtitle("加成率（%）") ///
    ytitle("频率") ///
    normal ///
    scheme(s2color)
graph export "output/figures/case05_18_markup_distribution.png", replace width(1200)

* 价格竞争力分析
gen price_position = 1 if price_diff_pct < -10
replace price_position = 2 if price_diff_pct >= -10 & price_diff_pct < 0
replace price_position = 3 if price_diff_pct >= 0 & price_diff_pct < 10
replace price_position = 4 if price_diff_pct >= 10 & !missing(price_diff_pct)
label define pos_lbl 1 "明显低于竞品" 2 "略低于竞品" 3 "略高于竞品" 4 "明显高于竞品"
label values price_position pos_lbl

display ""
tabulate price_position

graph bar (count), over(price_position) ///
    title("价格竞争力分布") ///
    ytitle("产品数量") ///
    scheme(s2color)
graph export "output/figures/case05_19_price_position.png", replace width(1200)

/*------------------------------------------------------------------------------
第六步：管理洞察和建议
------------------------------------------------------------------------------*/

display ""
display "=========================================="
display "=========================================="
display ""

display ""

display ""

display ""

display ""

display ""

/*------------------------------------------------------------------------------
第七步：输出总结
------------------------------------------------------------------------------*/

display ""
display "=========================================="
display "案例5：产品定价策略分析 - 完成"
display "=========================================="
display ""

display ""

display ""

display "✓ 构建高精度定价预测模型"
display "✓ 识别8个关键定价驱动因素"
display "✓ 生成19张可视化图表"
display "✓ 提供4种定价策略建议"
display "✓ 实现定价决策自动化"
display ""

/*------------------------------------------------------------------------------
第八步：清理资源
------------------------------------------------------------------------------*/

display ""
display "第八步：清理H2O资源"
display "--------------------"

* 关闭H2O
h2o shutdown, force

display ""
display "✓ H2O资源已清理"
display ""

log close

display ""
display "=========================================="
display "案例5分析完成！"
display "日志文件: output/case05_pricing_h2o.log"
display "图表目录: output/figures/"
display "=========================================="

